package com.fare.taluo.message;

import java.io.UnsupportedEncodingException;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
/**
 * 邮件发送
 * <p>通过javax.mail组装邮件数据，发送邮件，可带附件
 * <P>邮件初始化属性由{@link MessageConfiguration}装载
 * <p>示例：new SendEmail().setFrom("test@163.com").setTo("testTo@126.com").....可设置主题，抄送人等,
 * 	<br/>在设置好信息后，可调用.send()方法发送邮件
 * @author xiangsf 2012-12-8
 *
 */
public class SendEmail {
	
	protected Logger logger = Logger.getLogger(getClass());
	    protected MimeMessage mimeMsg;  //MIME邮件对象
	    protected Session session;      //邮件会话对象
	    protected Properties props;     //系统属性
	    protected Multipart mp;    //Multipart对象,邮件内容,附件等内容均添加到其中后再生成MimeMessage对象
	    protected EmailMessageProperties configuration;
	    
	    /**
	     *
	     */
	    public SendEmail() {
	    	configuration = MessageConfiguration.getInstance().getEmailProperties();
	    	if(configuration.isEmailServerSwitch()){
		    	//指定邮件服务器
		    	if (props == null) props = System.getProperties();      //获得系统属性对象
			    props.put("mail.smtp.host", configuration.getEmailSmtpServer());                 //设置SMTP主机
			    props.put("mail.smtp.auth", configuration.getEmailSmtpUser()==null || configuration.getEmailSmtpUser().trim()=="" ? "false" : "true");
			    props.put("mail.smtp.connectiontimeout", 10000); // 
			    props.put("mail.smtp.timeout", 10000);
			    session = Session.getInstance(props, null);   //获得邮件会话对象
			    mimeMsg = new MimeMessage(session);                 //创建MIME邮件对象
			    mp = new MimeMultipart();
			    if(logger.isDebugEnabled())
			    	logger.debug("初始化邮件成功!");
	    	}
	    }

	    /**
	     * 设置邮件主题
	     * @param mailSubject String
	     * @throws MessagingException 
	     */
	    public SendEmail setSubject(String mailSubject) throws MessagingException {
	    	if(configuration.isEmailServerSwitch()){  
	    		MessageAssert.hasText(mailSubject, "邮件主题");
	    		mimeMsg.setSubject(mailSubject);
	    	}
	          return this;
	    }


	    /**
	     * 设置邮件内容
	     * @param mailBody String
	     * @throws MessagingException 
	     */
	    public SendEmail setBody(String mailBody) throws MessagingException {
	    	System.out.println("mailBody:"+mailBody);
	    	if(configuration.isEmailServerSwitch()){
	            BodyPart bp = new MimeBodyPart();
	            StringBuilder builder = new StringBuilder();
	            builder.append("<meta http-equiv=Content-Type content=")
			            .append(configuration.getEmailContentType())
			            .append(" charset=")
			            .append(configuration.getEmailContentCharset())
			            .append(">")
			            .append(mailBody);
	           
	            bp.setContent(builder.toString(),  
	            		String.format("%s;charset=%s", configuration.getEmailContentType(), configuration.getEmailContentCharset()));
	            
	            mp.addBodyPart(bp);
	    	}
	            return this;
	    }


	    /**
	     * 设置邮件附件
	     * @param filename 文件名全路径
	     * @throws MessagingException 
	     */
	    public SendEmail setFileAffix(String filename) throws MessagingException {
	    	if(configuration.isEmailServerSwitch()){
		    	//忽略附件为空的
	    		 BodyPart bp = null;
	    		 FileDataSource fileds = null;
	    		 try{
			    	if(StringUtils.isNotBlank(filename)) {
			    		for(String f : filename.split(";")){
			    			if(StringUtils.isNotBlank(f)){
			    				bp = new MimeBodyPart();
			 		            fileds = new FileDataSource(filename);
			 		            bp.setDataHandler(new DataHandler(fileds));
			 		            try {//解决附件乱码问题
									bp.setFileName(MimeUtility.encodeText(fileds.getName(),"UTF-8","B"));
								} catch (UnsupportedEncodingException e) {
									e.printStackTrace();
								}
			 	
			 		            mp.addBodyPart(bp);
			    			}
			    		}
			    	}
	    		 }
	    		 finally{
	    			 bp = null;
	    			 fileds = null;
	    		 }
	    	}
	         return this;
	    }


	    /**
	     * 发件人设置，发件人不可为空
	     * @param from 发件人email地址
	     * @throws MessagingException 
	     */
	    public SendEmail setFrom(String from) throws MessagingException {
	    	if(configuration.isEmailServerSwitch()){
		    	MessageAssert.hasText(from, "发件人");
		        mimeMsg.setFrom(new InternetAddress(from.trim()));             //设置发信人
	    	}
	        return this;
	    }

	    /**
	     * 收件人设置，收件人不可为空
	     * @param to 收件人email地址
	     * @throws MessagingException 
	     */
	    public SendEmail setTo(String to) throws MessagingException {
	    	if(configuration.isEmailServerSwitch()){
		    	MessageAssert.hasText(to, "收件人");
		    	String[] mails = null;
		    	if(to.indexOf(";")>0){
		    		mails = to.split(";");
		    	}else if(to.indexOf(",")>0){
		    		mails = to.split(",");
		    	}else{
		    		mails = new String[]{to};
		    	}
				for(String m : mails){
					if(StringUtils.isNotBlank(m.trim()))
						mimeMsg.addRecipient(Message.RecipientType.TO, new InternetAddress(m.trim()));
				}
	    	}
			return this;
	    }

	    /**
	     * 抄送人
	     * @param copyto 抄送人email地址
	     * @throws MessagingException 
	     */
	    public SendEmail setCopyTo(String copyto) throws MessagingException {
	    	if(configuration.isEmailServerSwitch()){
	    		if(StringUtils.isNotBlank(copyto)){
	    			String[] mails = null;
			    	if(copyto.indexOf(";")>0){
			    		mails = copyto.split(";");
			    	}else if(copyto.indexOf(",")>0){
			    		mails = copyto.split(",");
			    	}else{
			    		mails = new String[]{copyto};
			    	}
					for(String m : mails){
						if(StringUtils.isNotBlank(m.trim()))
							mimeMsg.addRecipient(Message.RecipientType.CC, new InternetAddress(m.trim()));
					}
	    		}
	    	}
	         return this;
	    }

	    /**
	     * 发送邮件
	     * @throws MessagingException
	     */
	    public synchronized void send() throws MessagingException {
	    	if(configuration.isEmailServerSwitch()){ 
		    	Transport transport = null; 
		    	try{ 
		    		if(mimeMsg.getFrom() == null
		            		|| mimeMsg.getFrom().length == 0){
		            	//配置默认发送人
		            	mimeMsg.setFrom(new InternetAddress(configuration.getSendAddress()));
		            }
			    	mimeMsg.setContent(mp);
		            mimeMsg.saveChanges();
		            
		            transport = session.getTransport("smtp");
		            transport.connect(configuration.getEmailSmtpServer(), configuration.getEmailSmtpUser(), configuration.getEmailSmtpPwd());
		            transport.sendMessage(mimeMsg, mimeMsg.getAllRecipients());
		    	}finally{
		    		if(transport != null) transport.close();
		    	}
	    	}
	    }
	    public static void main(String[] arg0) throws MessagingException{
	    	new SendEmail().setSubject("测试多人接收邮件标题").setBody("测试多人接收邮件内容")
	    		.setTo("xiangshanfeng@foreveross.com;liaojinshi@foreveross.com;zengxiangqi@foreveross.com;ganhongzhi@foreveross.com;shijiejie@foreveross.com").setCopyTo(null).send();
	    	System.out.println("发送完毕!");
	    }

}
